package ch.uzh.ifi.sonar.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;

import ch.uzh.ifi.sonar.model.ModelFactory;
import ch.uzh.ifi.sonar.model.Module;
import ch.uzh.ifi.sonar.model.Stream;
import ch.uzh.ifi.sonar.storage.IStorage;
import ch.uzh.ifi.sonar.storage.TeneoHibernateStorage;

/**
 * wrapper for the directory traversing
 * 
 * @author Yi Guo
 * */

public class FileTraverser {

	private List<File> allFiles;

	private static final String[] SOURCES_EXTENSIONS = { ".c", ".cpp", ".h" };
	private static final String MET_EXTENSIONS = ".met";


	private interface MyOwnFilter {
		public boolean accept(String str);
	}

	private static class MetFilter implements MyOwnFilter {
		@Override
		public boolean accept(String str) {
			return str.endsWith(MET_EXTENSIONS);
		}
	}

	private static class SourceFilter implements MyOwnFilter {
		@Override
		public boolean accept(String fileName) {
			return fileName.endsWith(SOURCES_EXTENSIONS[0])
					|| fileName.endsWith(SOURCES_EXTENSIONS[1])
					|| fileName.endsWith(SOURCES_EXTENSIONS[2]);
		}

	}

	private void getSubFiles(File dir, MyOwnFilter filter) {
		if (dir.isDirectory()) {
			File[] subFiles = dir.listFiles();
			for (File aFile : subFiles) {
				if (aFile.isDirectory()) {
					getSubFiles(aFile, filter);
				} else if (aFile.isFile()) {
					String fileName = aFile.getName();
					if (filter.accept(fileName)) {
						allFiles.add(aFile);
					}
				}
			}
		} else if (dir.isFile()) {
			String fileName = dir.getName();
			if (filter.accept(fileName)) {
				allFiles.add(dir);
			}
		}
	}

	private void log(String string) {
		System.out.println("[INFO From FileTraverser: ]" + string);		
	}

	private void getSubSourceFiles(File dir) {
		getSubFiles(dir, new SourceFilter());
	}

	private void getSubMetFiles(File dir) {
		getSubFiles(dir, new MetFilter());
	}

	/** return all the source files, which end with '.c', '.cpp', or '.h' */
	public List<File> getAllSourceFiles(File dir) {
		allFiles = new ArrayList<File>();
		getSubSourceFiles(dir);
		return allFiles;
	}

	public List<File> getAllMetFiles(File dir) {
		allFiles = new ArrayList<File>();
		getSubMetFiles(dir);
		return allFiles;
	}

}
